package unimelb.discussiontracker.twitter.service.integration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;

import org.springframework.transaction.annotation.Transactional;

import unimelb.discussiontracker.twitter.data.dao.ITopicDao;
import unimelb.discussiontracker.twitter.data.entity.TopicEntity;

public abstract class AbstractFileProcessor implements IFileProcessor {

    protected SimpleDateFormat dateFormat;

    private ITopicDao topicDao;

    public void setDateFormat(SimpleDateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    public void setTopicDao(ITopicDao topicDao) {
        this.topicDao = topicDao;
    }

    @Override
    @Transactional
    public void process(File file, String masterTopic) {
        TopicEntity topic = topicDao.findByName(masterTopic);
        if (topic == null) {
            topic = new TopicEntity();
            topic.setText(masterTopic);

            topicDao.save(topic);
        }

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

            String line = null;
            while ((line = reader.readLine()) != null) {
                processLine(line, topic);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
            }
        }
    }

    protected abstract void processLine(String line, TopicEntity masterTopic);
}
